const fs = require('fs');
const path = require('path');
const readline = require('readline');
const log = require('./log.js');


function initFilePath(filePath) {
  if (!path.isAbsolute(filePath)) {
    filePath = path.join(__dirname, "..", filePath);
  }
  return filePath;
}

function readFileSync(filePath) {
  try {
    filePath = initFilePath(filePath);
    const data = fs.readFileSync(filePath, 'utf8') // 同步读取文件
    return data;
  } catch (error) {
    log.error(`读取文件${filePath}时发生错误:`, error);
    throw error; // 抛出错误
  }
}

function readJsonFileSync(filePath, throws = true, defaults = undefined) {
  try {
    filePath = initFilePath(filePath);
    const data = fs.readFileSync(filePath, 'utf8') // 同步读取文件
    const config = JSON.parse(data);
    return config;
  } catch (error) {
    if (throws) {
      throw error; // 抛出错误
    }
    return defaults || undefined;
  }
}

function readFilePromise(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

function readLineFile(filePath, closeCallback, readLineCallback) {
  filePath = initFilePath(filePath);
  const fileStream = fs.createReadStream(filePath);
  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  const lines = [];
  rl.on('line', (line) => {
    let l = line;
    if (readLineCallback) {
      l = readLineCallback(line);
    }
    lines.push(l);
  });
  rl.on('close', () => {
    closeCallback && closeCallback(lines);
  });
}

function joinPaths(arr = []) {
  let base = process.cwd();
  return arr.map(value => {
    return path.isAbsolute(value) ? value : path.join(base, value);
  });
}

function resolvePaths(arr = []) {
  return arr.map(value => {
    return path.isAbsolute(value) ? value : path.resolve(__dirname, "..", value);
  });
}

module.exports = { initFilePath, readFileSync, readJsonFileSync, readFilePromise, readLineFile, joinPaths, resolvePaths }
